<!-- 团购商品 -->
<template>
    <div class="common-layout">
        <el-backtop :bottom="50" target=".main" ref="backTop" :visibility-height="10"></el-backtop>
        <el-container>
            <el-header>
                <el-space>
                    <el-input class="fix_input" v-model.trim="seacherData.spuName" type="text" autocomplete="off"
                        placeholder="请输入商品名称" clearable @clear="init()" />
                    <el-input class="fix_input" v-model.trim="seacherData.id" type="text" autocomplete="off"
                        placeholder="请输入团购ID" clearable @clear="init()" />
                    <el-select class="frame" placeholder="请选择团购状态" v-model="seacherData.status">
                        <el-option v-for="item in groupStatus" :key="item.value" :label="item.name" :value="item.value" />
                    </el-select>
                    <el-button :icon="Search" type="primary" @click="search()">查找</el-button>
                    <el-button :icon="Plus" type="primary" @click="addRole();">添加</el-button>
                </el-space>
            </el-header>
            <el-main>
                <div class="el-scrollbar__wrap metaBox">
                    <el-backtop :bottom="100" ref="backTop" :visibility-height="5" target=".metaBox .el-scrollbar__wrap" />
                    <!-- 表格组件 -->
                    <el-table :data="tableData" border style="width: 100%;height: 100%;" class="scrollbar-demo-item"
                        v-loading="listLoading" element-londing-text="正在加载中...">

                        <el-table-column type="expand" style="width:100%">
                            <template #default="scope">
                                <el-descriptions :column="1" border>
                                    <el-descriptions-item label="类目ID" align="left" width="110px"><span>{{
                                        scope.row.categoryId }}</span>
                                    </el-descriptions-item>
                                    <el-descriptions-item label="商品sku属性" align="center">
                                        <el-table :data="scope.row.groupShopSkuDTOList" border
                                            :header-cell-style="{ 'text-align': 'center' }" id="table"
                                            :cell-style="{ 'text-align': 'center' }">
                                            <el-table-column prop="skuId" label="SKuId" />
                                            <el-table-column prop="title" label="规格标题" />
                                            <el-table-column prop="skuGroupShopPrice" label="团购价格(元)" />
                                            <el-table-column prop="stock" label="库存">
                                                <template #default="scope">
                                                    {{ scope.row.stock }}(件)
                                                </template>
                                            </el-table-column>
                                            <el-table-column prop="originalPrice" label="原始价格(元)" />
                                            <el-table-column prop="price" label="售卖价格(元)" />
                                            <el-table-column prop="vipPrice" label="会员价格(元)" />
                                            <el-table-column prop="barCode" label="国际条码" width="200px" />
                                        </el-table>
                                    </el-descriptions-item>
                                </el-descriptions>
                            </template>
                        </el-table-column>

                        <el-table-column prop="id" label="团购ID" align="center" />
                        <el-table-column prop="spuId" label="商品ID" align="center" />
                        <el-table-column prop="title" label="商品名称" align="center" width="200" />
                        <el-table-column prop="img" label="商品主图" align="center" width="100">
                            <template #default="scope">
                                <el-popover trigger="hover" placement="right" v-if="scope.row.img">
                                    <template #reference>
                                        <el-image :src="scope.row.img" style="width:35px;height:50px;" />
                                    </template>
                                    <template #default>
                                        <el-image :src="scope.row.img" style="width:148px;height:180px;" />
                                    </template>
                                </el-popover>
                                <el-tag type="info" v-else>类型无需图片</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="automaticRefund" label="未清策略" align="center" width="100">
                            <template #default="scope">
                                <el-tag :type="scope.row.automaticRefund == 1 ? 'success' : 'warning'">
                                    {{ scope.row.automaticRefund == 1 ? '退货' : '发货' }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="status" label="活动状态" align="center" width="100">
                            <template #default="scope">
                                <el-tag :type="scope.row.status == 1 ? 'success' : 'danger'">
                                    {{ scope.row.status == 1 ? '进行' : '冻结' }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="gmtStart" label="开始时间" align="center" width="200">
                            <!-- 时间转换 -->
                            <template #default="scope">
                                {{ scope.row.gmtStart ? handleTime(scope.row.gmtStart, '-ymdhmms') : "无" }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="gmtEnd" label="结束时间" align="center" width="200">
                            <!-- 时间转换 -->
                            <template #default="scope">
                                {{ scope.row.gmtEnd ? handleTime(scope.row.gmtEnd, '-ymdhmms') : "无" }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="sales" label="当前人数" align="center" width="100" />
                        <el-table-column prop="minNum" label="目标人数" align="center" width="100" />
                        <el-table-column label="操作" align="center" width="180">
                            <template #default="scope">
                                <el-button type="primary" :disabled="scope.row.status == 1"
                                    @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                                <el-button type="danger" :disabled="scope.row.status == 1"
                                    @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-main>
            <el-footer>
                <Paging v-bind="pagination" @page-change="pageChange" />
            </el-footer>
        </el-container>
    </div>

    <!-- 抽屉组件 -->
    <el-drawer v-model="visible" :show-close="false" direction="ltr" size="55%" @close="drawerClose">
        <template #header="{ close, titleId, titleClass }">
            <h4 :id="titleId" :class="titleClass">{{ dialogTitle }}团购商品</h4>
            <el-button @click="close">取消</el-button>
            <el-button type="primary" @click="sure(ruleFormRef);">{{ dialogTitle }}</el-button>
        </template>
        <el-card class="box-card">

            <h5>商品属性(spu)</h5>
            <el-form ref="ruleFormRef" :model="dataForm" :rules="rules" status-icon class="demo-ruleForm"
                label-width="180px">
                <el-form-item prop="spuId" label="团购商品">
                    <el-cascader :options="options" clearable :props="props" v-model="dataForm.spuId"
                        @change='handleChange' />
                </el-form-item>
                <el-form-item prop="gmtEnd" label="团购时间">
                    <el-space>
                        <el-col :span="11">
                            <el-date-picker v-model="dataForm.gmtStart" type="datetime" placeholder="开始时间"
                                value-format="x" />
                        </el-col>
                        <el-col :sapn="2">至</el-col>
                        <el-col :span="11">
                            <el-date-picker v-model="dataForm.gmtEnd" type="datetime" placeholder="结束时间" value-format="x" />
                        </el-col>
                    </el-space>
                </el-form-item>
                <el-form-item prop="minNum" label="团购基础人数">
                    <el-input-number v-model.trim="dataForm.minNum" class="mx-4" :min="1" controls-position="right" />
                </el-form-item>
                <el-form-item label="活动结束时人数没有达到基础人数采取：">
                    <el-radio-group v-model="dataForm.automaticRefund">
                        <el-radio-button label="0">不退款,我要发货</el-radio-button>
                        <el-radio-button label="1">自动退款,我不发货</el-radio-button>
                    </el-radio-group>
                </el-form-item>

            </el-form>

        </el-card>

        <el-card class="box-card">
            <div>
                <div style="display: flex;justify-content: space-between;">
                    <h5>商品类型(sku)</h5>
                    <el-popover placement="right" :width="400" trigger="click" @hide="updataData.skuGroupShopPrice = 1">
                        <template #reference>
                            <el-button ref="refBtnSetAllPrice" type="primary" :plain="true" size="large"
                                :disabled="skuList.skudList.length == 0">
                                批量定价
                            </el-button>
                        </template>
                        <el-form ref="specForm" status-icon label-position="left" style="width:400px;margin-left: 50px;">
                            <el-form-item label="团购价格">
                                <el-input-number v-model.number="updataData.skuGroupShopPrice" :min="1"
                                    controls-position="right" />
                                <span>元</span>
                            </el-form-item>
                            <el-form-item>
                                <el-button @click="refBtnSetAllPrice.$el?.click?.()">取消</el-button>
                                <el-button type="primary"
                                    @click="handGroupPrice(); refBtnSetAllPrice.$el?.click?.()">确认</el-button>
                            </el-form-item>
                        </el-form>
                    </el-popover>
                </div>

                <el-table :data="skuList.skudList" border :header-cell-style="{ 'text-align': 'center' }" id="table"
                    :cell-style="{ 'text-align': 'center' }">
                    <el-table-column prop="id" label="SkuId" />
                    <el-table-column prop="barCode" label="Sku条形码" />
                    <el-table-column prop="title" label="类型名" />
                    <el-table-column prop="stock" label="库存" width="100" />
                    <el-table-column prop="price" label="现价/元" width="100" />
                    <el-table-column prop="skuGroupShopPrice" label="团购价格/元" />
                    <el-table-column label="操作" align="center">
                        <template #default="scope">
                            <el-button type="primary" @click="handleupdate(scope.$index, scope.row)">更新</el-button>
                        </template>
                    </el-table-column>

                </el-table>
            </div>

            <div>
                <el-dialog v-model="dialogVisible" title="更新团购价格" width="700px" destroy-on-close
                    @close="updataData.skuGroupShopPrice = 1">
                    <el-form style=" margin-left: 50px;margin-right: 50px;" :model="updataData" status-icon>
                        <el-form-item label="团购价格" prop="prise" label-width="100px">
                            <el-input-number v-model.number="updataData.skuGroupShopPrice" :min="1" :max="999999"
                                controls-position="right" />
                        </el-form-item>
                        <el-form-item label="现价" label-width="100px">
                            {{ updataData.price }}
                        </el-form-item>
                        <el-form-item label="skul类型名" label-width="100px">
                            {{ updataData.title }}
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="dialogVisible = false">取消</el-button>
                            <el-button type="primary" @click="handleonce()">
                                确认
                            </el-button>
                        </span>
                    </template>
                </el-dialog>
            </div>
        </el-card>
    </el-drawer>
</template>
  
<script lang="ts" setup>
import { Search, Plus } from '@element-plus/icons-vue'
import { ElMessageBox, ElNotification, type FormInstance, type UploadProps } from 'element-plus'
import { post } from '@/utils/http';
import { computed, nextTick, onMounted, reactive, ref } from 'vue';
import Paging from '@/components/paging/Paging.vue'
import { ClassPagination, ClassGroupShop } from '#/index';
import { ElMessage } from "element-plus"
import { handleTime, traversalTime } from '@/utils/ProcessingTime'
import cookie from 'js-cookie'
import { initobj } from '@/utils'
// 数据初始化
onMounted(() => {
    init()
})
const sKudList: TypeGroupShopSku[] = reactive([]) //渲染内层表的数据
const skuList: any = reactive({ skudList: [] })//团购商品列表
// 控制对话框组件的显示隐藏
const dialogVisible = ref(false)
// 控制抽屉组件的显示隐藏
const visible = ref(false)
const options: Array<any> = reactive([])    //类目树结构
const backTop = ref()                                   //回到顶部
const pagination = reactive(new ClassPagination())      //分页
let listLoading = ref(false)            //加载效果
const dialogTitle = ref("")             //判断添加和修改

const refBtnSetAllPrice = ref()
const ruleFormRef = ref<FormInstance>()
const tableData: ClassGroupShop[] = reactive([])    //表格数据
/**
 * 表单数据
 */
// 添加传递的数据

// const dataForm = reactive(new ClassAdvert())
/**
  * 请求添加传递的参数
  */
let dataForm = reactive({
    spuId: "",          //spuId
    gmtStart: "",       //团购开始时间戳
    gmtEnd: "",         //团购结束时间戳
    minNum: 1,         //团购最低人数
    automaticRefund: 0,//团购人数未满是否自动退款
    groupShopSkuList: "" //团购sku链表
})

/**
  * 点击修改数据
  */
let updataData = reactive({
    _index: 0,
    price: 0,    //现价
    skuGroupShopPrice: 0,//团购价
    title: '',//sku类型名
})
/**
 * 添加时清空参数
 */
let newForms = { ...dataForm }


/**
* 搜索所需的数据
*/
// 搜索需要的数据
let seacherData = reactive({
    id: "",      //团购商品的ID
    spuName: '', //团购商品的名称
    status: '',  //团购商品的状态
})
/**
* 商品树配置选项
*/
const props = {
    checkStrictly: false,
    emitPath: false,
    children: "children",
    value: "id",
    label: "label"
}

/**
  * 团购商品状态
  */
const groupStatus = [
    { value: 0, name: "冻结" },
    { value: 1, name: "进行" }
];

/**
 * 表单验证
 */
const rules = {
    spuId: [
        { required: true, message: "请选择团购商品！", trigger: 'change' },
    ],
    gmtEnd: [
        { required: true, trigger: 'change', message: "请选择团购时间！" },
    ],
    minNum: [
        { required: true, message: "请输入基础人数", trigger: 'change' }
    ],

}

/**
 * 获取初始化数据，用于渲染页面
 */
function init() {
    listLoading.value = true
    // 请求管理员列表需要传递的参数
    let groupshopListData = reactive({
        _gp: "admin.groupshop",
        _mt: "list",
        id: seacherData.id,
        spuName: seacherData.spuName,
        status: seacherData.status,//用户状态
        page: pagination.page,//当前页码
        limit: pagination.limit//每页页码长度
    })
    // 请求管理员列表接口拿到管理员列表信息
    post(groupshopListData).then(res => {
        console.log("====管理员数据======");
        console.log(res);
        let { data: { total, items }, errno, errmsg } = res
        if (200 === errno) {
            pagination.total = total
            console.log(items);

            sKudList.length = 0
            tableData.length = 0;
            res.data.items.forEach((item: TypeGroupying) => {
                sKudList.push(...item.groupShopSkuDTOList)
            });
            tableData.push(...items)
            listLoading.value = false
            nextTick(() => {
                backTop.value.$el.click?.()
            })
        } else {
            ElMessage.error(errmsg)
        }
    }).catch(err => {
        console.log(err);

    })
}

// 搜索操作
function search() {
    init()
}

//子传父的自定义事件
function pageChange(e: TypePage) {
    pagination.page = e.page
    pagination.limit = e.limit
    init()
}

getGoodsData()

/**
 * 请求商品数据
 */
function getGoodsData() {
    post({
        _gp: "admin.product",
        _mt: "getSpuBigTree"
    }).then(res => {
        console.log(res.data)
        let { errmsg, errno } = res
        if (200 == errno) {
            options.length = 0
            options.push(...res.data)

        } else {
            ElMessage.error(errmsg)
        }

    })
}

// 添加操作
function addRole() {
    dialogTitle.value = "创建"
    Object.assign(dataForm, newForms)
    // initobj(dataForm, {})
    visible.value = true;
    console.log(dataForm)
}

/**
 * 关闭抽屉组件清空数据
 */
function drawerClose() {
    skuList.skudList = []
    // options.length = 0;

    ruleFormRef.value?.resetFields()
}



/**
 * 获取修改前的数据
 * @param index 当前下标
 * @param row 当前下标的数据
 */
const handleEdit = (index: number, row: ClassGroupShop) => {
    dialogTitle.value = "修改"
    Object.assign(dataForm, row)
    skuList.skudList.length = 0;
    // 深克隆
    (row.groupShopSkuDTOList || []).forEach(item => {
        skuList.skudList.push(Object.assign({}, item))
    });

    getGoodsData()      //请求商品数据
    visible.value = true;


}



/**
  * 点击更新
  */
function handleupdate(index: number, row: TypeGroupShopSku) {
    dialogVisible.value = true
    // updateType.value = true
    Object.assign(updataData, row)
    // skuList.skudList[index].skuGroupShopPrice = updataData.skuGroupShopPrice
    updataData._index = index  //存当前行下标
}

/**
  * 确定更新
  */
function handleonce() {
    if (updataData.skuGroupShopPrice > updataData.price) {
        ElNotification.warning('团购价格不能大于现价')
        return false
    }
    if (updataData.skuGroupShopPrice === null) return ElMessage.error('必须填写价格')
    skuList.skudList[updataData._index].skuGroupShopPrice = updataData.skuGroupShopPrice

    dialogVisible.value = false
    ElNotification.success('更新成功！！')
}
/**
 * 确定修改
 */
function handGroupPrice() {
    if (skuList.skudList.some((node: { price: number; }) => node.price < updataData.skuGroupShopPrice)) return ElMessage.error('团购价格不能高于现价')
    skuList.skudList.map((item: TypeGroupShopSku) => {
        item.skuGroupShopPrice = updataData.skuGroupShopPrice
        return
    })
    if (updataData.skuGroupShopPrice >= 1) {

        ElNotification.success('修改成功')

    }
    dialogVisible.value = false
}

/**
 * 添加和修改功能
 *  * @param formEl 表单验证结果
 */
function sure(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {

            if (!dataForm.gmtStart || !dataForm.gmtEnd || dataForm.gmtEnd < dataForm.gmtStart) {
                ElMessage.error("请选择正确的日期")
                return false
            }
            try {
                skuList.skudList.forEach((item: TypeGroupShopSku) => {
                    item.skuId = item.id
                    if (!item.skuGroupShopPrice) {
                        throw Error
                    }
                })
            } catch (err) {
                ElNotification.error('团购价格不能为空')
                return
            }

            dataForm.groupShopSkuList = (JSON.stringify(skuList.skudList))
            console.log("=====要提交的表单数据=====");
            console.log(dataForm);
            let data = {
                _gp: 'admin.groupshop',
                _mt: dialogTitle.value == '修改' ? 'edit' : 'create',
                ...dataForm
            }
            post(data).then(res => {
                console.log(res);

                let { errno, errmsg } = res
                if (200 === errno) {
                    dialogVisible.value = false
                    visible.value = false
                    ElNotification.success(dialogTitle.value == '修改' ? '修改成功' : '添加成功')
                    init()
                } else {
                    ElNotification.error(errmsg)
                }
            }).catch(err => {
                console.log(err);
            })
        } else {
            return false
        }
    })
}



/**
   * 点击节点
   */
function handleChange() {
    post({
        _gp: "admin.product",
        _mt: "detail",
        spuId: dataForm.spuId
    }).then(res => {
        console.log(res)
        if (200 == res.errno) {
            skuList.skudList.length = 0
            skuList.skudList = res.data.skuList         //抽屉组件商品类型表格数据
        } else {
            skuList.skudList.length = 0
            ElNotification.error(res.errmsg)
        }
    })
}


/**
 * 删除操作
 * @param index 当前下标
 * @param row 当前下标的数据
 */
const handleDelete = (index: number, row: TypeAdvert) => {

    let data = {
        _gp: 'admin.groupshop',
        _mt: 'delete',
        id: row.id
    }

    ElMessageBox.confirm('真的要删除吗？')
        .then(() => {
            post(data).then(res => {
                console.log(res);

                let { errno, errmsg } = res
                if (200 === errno) {
                    ElMessage.success('删除成功')
                    init()
                } else {
                    ElMessage.error(errmsg)
                }

            }).catch(err => {
                console.log(err);
            })
        })
        .catch(() => {
            ElMessage.error("取消删除！")
        })
}
</script>
  

<style scoped lang="less">
.metaBox {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 60vh;
    text-align: center;
}

.fix_input {
    width: 200px;
}

.treechile {
    position: relative;
    right: 0px;
    color: red;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.box-card {
    width: 100%;
}
</style>